package org.lt.ttkv;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author
 * @date 2023/7/6.
 * description：
 */
class BaseActivity<VB extends ViewBinding> extends AppCompatActivity {
    protected VB viewBinding = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindView();
    }

    private void bindView() {
        int layoutRes=getLayoutRes();
        if (layoutRes==-1){
            return;
        }
        ViewGroup layoutRootView = (ViewGroup) LayoutInflater.from(this).inflate(layoutRes, null);
        viewBinding = injectViewBinding(this, layoutRootView);
        setContentView(viewBinding.getRoot());
    }
    public static <VB extends ViewBinding> VB injectViewBinding(
            Activity activity, View root) {
        Type type = activity.getClass().getGenericSuperclass();
        VB viewBinding = getViewBindingByView(type, root);
        if (viewBinding != null) {
            activity.setContentView(viewBinding.getRoot());
        } else {
            activity.setContentView(root);
        }
        return viewBinding;
    }
    private static <VB extends ViewBinding> VB getViewBindingByView(Type type, View root) {
        VB viewBinding = null;
        if (type instanceof ParameterizedType) {
            ParameterizedType genericType = (ParameterizedType) type;
            Type[] typeArguments = genericType.getActualTypeArguments();

            Type viewBindingType = null;
            for (Type argumentType : typeArguments) {
                if (ViewBinding.class.isAssignableFrom((Class) argumentType)) {
                    viewBindingType = argumentType;
                    break;
                }
            }
            if (viewBindingType != null) {
                try {
                    Method inflate = ((Class<?>) viewBindingType).getDeclaredMethod("bind", View.class);
                    viewBinding = (VB) inflate.invoke(null, root);
                } catch (NoSuchMethodException | IllegalAccessException |
                         InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return viewBinding;
    }
    public int getLayoutRes(){
        return -1;
    }
}
